/**
 * ------------------------------------------------------
 *  登录页
 * ------------------------------------------------------
 *
 * Note: .
 *
 */
import {Card,Form,Input,Button, message} from 'antd'
import {useNavigate} from 'react-router-dom'
import { MD5 } from 'crypto-js'
import { loginAPI } from '@/apis/user'
import useStore from '@/store/modules/user'
import './index.scss'
import logo from '@/assets/logo.png'

const Login = () => {
    
    const { setToken } = useStore()
    const navigate = useNavigate()
    const [messageApi,contextHolder] = message.useMessage();
    const fetchLogin = async (loginForm) => {
        const res = await loginAPI(loginForm);
        if (res.code === 401001) {
          return res.msg;
        }
        setToken(res.data.token);
        return 'ok';
      };
    //提交登录表单
    const onFinish = async (formValue) =>{
        const { username,password } = formValue
        //构建登录接口所需的参数用户名/MD5加密的密码
        const reqData = {
            username,
            password:MD5(password).toString()
        }

        //触发异步 fetchLogin
        const res = await fetchLogin(reqData)
        if(res==='ok'){
            //提示用户登录成功
            messageApi.success('登录成功',1,()=>{
                navigate('/') //跳转到首页
            })
        }else{
            //登录失败，显示接口返回的错误信息
            messageApi.error(res)
        }
    }
    return(
        <div className="login">
            <Card className="login-container">
                <img className="login-logo" src={logo} alt="" />
                {/** 登录表单 */}
                <Form onFinish={onFinish} validateTrigger="onBlur">
                    <Form.Item
                        name="username"
                        rules={[
                            {
                            required:true,
                            message:'请输入用户名'
                            },
                        ]}>
                        <Input size="large" placeholder="请输入用户名" />
                    </Form.Item>
                    <Form.Item
                        name="password"
                        rules={[
                            {
                            required:true,
                            message:'请输入密码'
                            },
                        ]}>
                        <Input.Password size="large" placeholder="请输入密码" />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit" size="large" block>
                            登录
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
            {contextHolder}
        </div>
    )
}

export default Login